package com.hp.ssmp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hp.ssmp.dao.UserMapper;
import com.hp.ssmp.entity.TUser;
import com.hp.ssmp.service.UserService;
import com.hp.ssmp.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service("userService")
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper,TUser> implements UserService {

    @Autowired
    private UserMapper userMapper;

    public boolean addUser(TUser user) {
        String salt = PasswordUtil.salt();
        String password = PasswordUtil.encode(user.getPassword(), salt);
        user.setSalt(salt);
        user.setPassword(password);
        user.setStatus(1L);
        user.setType(2L);
        return userMapper.insert(user) > 0;
    }

    public TUser login(String usercode, String password) {
        QueryWrapper<TUser> wrapper = new QueryWrapper<TUser>();
        wrapper.eq("USERCODE",usercode);
        TUser user = userMapper.selectOne(wrapper);
        if(user != null && user.getPassword().equals(PasswordUtil.encode(password,user.getSalt()))){
            return user;
        }else{
            return null;
        }

    }

    public Page<TUser> getUserPage(Integer currentPage, Integer pageSize, Long sex) {
        //封装分页对象
        Page<TUser> page = new Page<TUser>(currentPage,pageSize);
        //封装动态条件查询对象
        QueryWrapper<TUser> wrapper = new QueryWrapper<TUser>();
        if(null != sex && !"".equals(sex)){
            wrapper.eq("sex",sex);
        }
        return userMapper.selectPage(page,wrapper);
    }

    @Override
    public boolean updatePwd(Long userid, String password, String newpassword) {
        TUser tUser = userMapper.selectById(userid);
        Boolean oldPwdTrue=tUser.getPassword().equals(PasswordUtil.encode(password,tUser.getSalt()));
        if(oldPwdTrue){
            String salt = PasswordUtil.salt();
            String nowpassword = PasswordUtil.encode(newpassword, salt);
            tUser.setPassword(nowpassword);
            tUser.setSalt(salt);
            userMapper.updateById(tUser);
            return true;
        }
        return false;
    }
}
